/**
 * Created by hsia on 2017/4/26.
 */
var orgTree,vkey,demoIframe,rsetting;
var tips = true;
var lastValue = "", nodeList = [], fontCss = {color:"blue", "font-weight":"bold"};
var videoMap = new Map();

var realTimeMonitJs = function (targetObj) {
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.init();
    return this;
};

realTimeMonitJs.prototype={
    init:function(){

        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find(".search-panel"));
        var bindFunctionArray = [{fName:"gateOpen",fs:this.gateOpen},{fName:"gateClose",fs:this.gateClose},{fName:"play",fs:this.play}];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        this.loadtree();
        demoIframe = $(".resource-panel");
        demoIframe.bind("load", this.loadReady);
        vkey = $("#vkey");
        vkey.bind("focus", this.focusvkey)
            .bind("blur", this.blurvkey)
            .bind("propertychange", this.searchNode)
            .bind("input", this.searchNode);
        //this.webS = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, this.targetObj);
       /* $("#collapseAllBtn").bind("click", {type:"collapseAll",id:"collapseAllBtn"}, this.expandNode);
        $("#expandAllBtn").bind("click", {type:"expandAll",id:"expandAllBtn"}, this.expandNode);*/
    },
    //树加载
    loadtree:function () {
        rsetting = {
            check: {
                enable: true,
                nocheckInherit: false
            },
            view: {
                dblClickExpand: true,
                showLine: true,//显示-/+连线
               // selectedMulti: false,
                fontCss: this.getFontCss,

            },
            data: {
                simpleData: {
                    enable:true,
                    idvkey: "id",
                    pIdvkey: "pId",
                    rootPId: ""
                }
            },
            async: {
                enable: true,
                type:"post",
                url:baseApiPath+"centralized/ztreeData",
                dataFilter: this.filter
            },
            callback: {
                //beforeClick: this.BeforeClick,
                onCheck: this.Checked,
                onAsyncSuccess: this.zTreeOnAsyncSuccess,
                onClick: this.Onclick
            }

        };
        orgTree= $.fn.zTree.init($("#orgTree"), rsetting);

    },
    Checked:function (event, treeId, treeNode) {
        var nodes = orgTree.transformToArray(orgTree.getCheckedNodes(true));
        if(treeNode.checked){//新增
            if(nodes.length<3){
                realTime.addChnViewer(treeNode);
            }else{
                treeNode.checked=false;
                orgTree.updateNode(treeNode);
                notification({ title:"友情提示",message:"只能同时观看两个闸道监控!!"},'info');
            }
        }else{//删除
            realTime.cancelChnViewer(treeNode);
        }
    },
    Onclick:function (e,treeId,treeNode) {
        orgTree.expandNode(treeNode);
    },
    resetTree:function () {//恢复tree
        $.fn.zTree.init($("#orgTree"), rsetting);
    },
    expandNode:function (e) {//节点展开 折叠
        orgTree = $.fn.zTree.getZTreeObj("orgTree"),
            type = e.data.type,
            cid = e.data.id,
            nodes = orgTree.getSelectedNodes();
        $(".tree-button a").each(function () {
            if(this.id == cid){
                this.className = "select";
            }else{
                this.className ='';
            }
        });
        if (type.indexOf("All")<0 && nodes.length == 0) {
            notification({ title:"操作失败",message:"请先选择一个父节点!!"},'info');
        }

        if (type == "expandAll") {
            orgTree.expandAll(true);
        } else if (type == "collapseAll") {
            orgTree.expandAll(false);
        } else {
            var callbackFlag = $("#callbackTrigger").attr("checked");
            for (var i=0, l=nodes.length; i<l; i++) {
                orgTree.setting.view.fontCss = {};
                if (type == "expand") {
                    orgTree.expandNode(nodes[i], true, null, null, callbackFlag);
                } else if (type == "collapse") {
                    orgTree.expandNode(nodes[i], false, null, null, callbackFlag);
                } else if (type == "toggle") {
                    orgTree.expandNode(nodes[i], null, null, null, callbackFlag);
                } else if (type == "expandSon") {
                    orgTree.expandNode(nodes[i], true, true, null, callbackFlag);
                } else if (type == "collapseSon") {
                    orgTree.expandNode(nodes[i], false, true, null, callbackFlag);
                }
            }
        }
    },
    focusvkey:function(e){
        if (vkey.hasClass("empty")) {
            vkey.removeClass("empty");
        }
    },
    blurvkey:function(e){
        if (vkey.get(0).value === "") {
            vkey.addClass("empty");
        }
    },
    searchNode:function(e){//根据值模糊搜索
        orgTree ==null?$.fn.zTree.init($("#orgTree"), rsetting): $.fn.zTree.getZTreeObj("orgTree");
        //orgTree= $.fn.zTree.init($("#orgTree"), rsetting);
        var views = orgTree.setting.view;
        views["fontCss"] = orgTree.getFontCss;
        var value = $.trim(vkey.get(0).value);
        realTime.setColor('name',value);


        orgTree.expandAll(true);
        var vkeyType = "name";
        if (vkey.hasClass("empty")) {
            value = "";
        }
        if (lastValue === value) return;
        lastValue = value;
        if (value === "") return;
    },
    updateNodes:function(highlight) {//更新节点
        orgTree ==null?$.fn.zTree.init($("#orgTree"), rsetting): $.fn.zTree.getZTreeObj("orgTree");
        var allNode = orgTree.transformToArray(orgTree.getNodes());
        for(var i=0,l=allNode.length;i<l;i++){
            allNode[i].highlight = false;
            orgTree.updateNode(allNode[i]);
        }
        for( var i=0, l=nodeList.length; i<l; i++) {
            var array = nodeList[i].getPath();
            for(var a=0,b=array.length;a<b;a++){
                array[a].highlight = highlight;
                orgTree.updateNode(array[a]);
            }
        }
        realTime.nodeView();
    },
    nodeView:function () {
        var that = this;
        orgTree ==null?$.fn.zTree.init($("#orgTree"), rsetting): $.fn.zTree.getZTreeObj("orgTree");
        var allNode = orgTree.transformToArray(orgTree.getNodes());

        for(var i=0,l=allNode.length;i<l;i++){
            if(nodeList && nodeList.length > 0 ){
                if(!allNode[i].highlight){
                    that.targetObj.find('#'+allNode[i].tId).hide();
                }else{
                    that.targetObj.find('#'+allNode[i].tId).show();
                }
            }else{
                allNode[i].highlight=false;
                that.targetObj.find('#'+allNode[i].tId).hide();
            }

        }
    },
    getFontCss:function(treeId, treeNode) {
        return (!!treeNode.highlight) ? {color:"#0000FF", "font-weight":"bold","font-size":"14px"} : {color:"#000", "font-weight":"normal"};
    },
    reSetFontCss:function (treeId, treeNode) {
        return (!treeNode.highlight)?{color:"#000000", "font-weight":"normal"}:{};
    },
    setColor:function (vkey,value) {
        var that = this;
        orgTree ==null?$.fn.zTree.init($("#orgTree"), rsetting): $.fn.zTree.getZTreeObj("orgTree");
        nodeList = orgTree.getNodesByParamFuzzy(vkey, value);
        if(value != ""){
            realTime.updateNodes(true);
        }else{
            var views = orgTree.setting.view;
            views["fontCss"] = orgTree.reSetFontCss;
            orgTree.refresh();
        }
        if(nodeList && nodeList.length == 0){
            that.targetObj.find('#tips').show();
        }else{
            that.targetObj.find('#tips').hide();
        }
    },
    filter:function(treeId, parentNode, responseData){

        return JSON.parse(responseData.results);
    },
    zTreeOnAsyncSuccess:function (event, treeId, treeNode, msg) {//捕获异步加载正常结束的事件回调函数
        orgTree = $.fn.zTree.getZTreeObj(treeId);
        var allNode = orgTree.transformToArray(orgTree.getNodes());
        var initCheck = 0;
        orgTree.expandAll(true);//甭管你多牛逼,都给我展开
        for(var n in allNode){
            if(initCheck==2){
                return;
            }
            if(allNode[n].gpc=='chn_in' || allNode[n].gpc=='chn_out'){
                initCheck +=1;
                allNode[n].checked = true;
                orgTree.updateNode(allNode[n]);
                realTime.addChnViewer(allNode[n]);
            }
        }
    },
    addChnViewer:function (node) {
        var that = this;
        JsonpAjax(baseApiPath+"centralized/selChnMonit?id=" + node.id,null,"json",function(result){
            var data = result;
            var pathName = data.pathName;
            pathName = pathName.substring(pathName.indexOf(',')+1,pathName.length).replaceAll(',','—');
            var chnHtml = '<div class="basicInfo-monitor" id="'+data.organizationCode+'">'
                +   '       <div class="title"><span>'+pathName+'</span>'
                +   '           <div class="brakeBtn2">'
                +   '               <a onclick="realTime.gateOpen(this)"><img src="images/btn2-open.png" /></a>'
                +   '               <a onclick="realTime.gateClose(this)"><img src="images/btn2-close.png" /></a>'
                +   '           </div>'
                +   '       </div>'
                +   '           <div class="list">'
                +   '               <div style="width:100%" id="loop">'
                +   '               </div>'
                +   '       </div>'
                +   '</div>';
            that.targetObj.find("#chnViewer").append(chnHtml);
            var equs = data.equs;
            var equHtml='';
            if(equs!=undefined && equs.length>0){
                for(var i in equs){
                    var jsonData={};
                    jsonData['ipAddress']=equs[i].equipmentManagements.basic.ip;
                    jsonData['port']=equs[i].equipmentManagements.basic.port;
                    jsonData['deviceType']=equs[i].equipmentManagements.basic.deviceid;
                    jsonData['userName']=equs[i].equipmentManagements.account.loginName;
                    jsonData['pwd']=equs[i].equipmentManagements.account.loginPsw;
                    jsonData['code']=equs[i].organizationCode;
                    var jsonStr = JSON.stringify(jsonData).replaceAll('"','&quot;');
                    equHtml += '<div class="monitor">'
                        +   '       <div class="monitorName">'+equs[i].organizationName+'</div>'
                        +   '       <div class="monitorArea" id="'+equs[i].organizationCode+'"></div>'
                        +   '       <div class="monitorBtn">'
                        +   '            <div class="switch-button" style="width:100%">'
                        +   '                 <div class="checkbox">'
                        +   '                      <input type="checkbox" data-value="'+jsonStr+'"  value="rtsp://'+equs[i].equipmentManagements.basic.ip+'/stream_main" onclick=realTime.play(this) />'
                        +   '                      <label></label>'
                        +   '                 </div>'
                        +   '            </div>'
                        +   '       </div>'
                        +   ' </div>';
                    that.showVideo(that.targetObj.find('#'+equs[i].organizationCode),jsonData);
                }
            }
            that.targetObj.find("#"+data.organizationCode+" #loop").append(equHtml);

        });
    },
    cancelChnViewer:function (node) {
        var that = this;
        that.targetObj.find("#"+node.id).remove();
    },
    dblClickExpand:function(treeId, treeNode){//双击节点事件
        return treeNode.level > 0;
    },
    loadReady:function(){
        var bodyH = demoIframe.contents().find(".tree-structure").get(0).scrollHeight,
            htmlH = demoIframe.contents().find("#OrgTreeDiv").get(0).scrollHeight,
            maxH = Math.max(bodyH, htmlH), minH = Math.min(bodyH, htmlH),
            h = demoIframe.height() >= maxH ? minH:maxH ;
        if (h < 530) h = 530;
        demoIframe.height(h);
    },
    gateClose:function (e) {//关闭闸道
        return;
        var that = this;
        var chnId = $(e).parents(".basicInfo-monitor")[0].id;
        var node = orgTree.getNodeByParam('id',chnId,null);
        if(node){
            var pathId = node.pathIds;
            pathId = 'park/'+pathId.replaceAll(',','/')+'/MR/F1';
            if(chnId){
                that.webS.sendMsgToWebSocket({operateType:0,operateMode:1},'OG',pathId);
            }
            return;
        }
        notification({ title:"操作失败",message:"请清理缓存,并重启浏览器!!"},'info');
    },
    gateOpen:function (e) {//开启闸道
        return;
        var that = this;
        var chnId = $(e).parents(".basicInfo-monitor")[0].id;
        var node = orgTree.getNodeByParam('id',chnId,null);
        if(node){
            var pathId = node.pathIds;
            pathId = 'park/'+pathId.replaceAll(',','/')+'/MR/F1';
            if(chnId){
                that.webS.sendMsgToWebSocket({operateType:1,operateMode:1},'OG',pathId);
            }
           return;
        }
        notification({ title:"操作失败",message:"请清理缓存,并重启浏览器!!"},'info');
    },
    play:function (obj) {
        var jsonData = JSON.parse($(obj).attr('data-value'));
        var ax = realTime.targetObj.find('#'+jsonData.code);
        if(obj.checked){
            realTime.openRealVideo(ax,jsonData);
        }else{
            realTime.closeRealVideo(ax,videoMap.get(jsonData.code));
        }
    },
    handlerMessage:function (e) {
        if(typeof e.data !="object"){
            return;
        }
        var info = JSON.parse(e.data);
        if('F1'==info.msgType){
            var chnId = info.data.channelCode;
            var node = orgTree.getNodeByParam('id',chnId,null);
            if(node){
                var pathName = node.pathName;
                pathName = pathName.substring(pathName.indexOf(',')+1,pathName.length).replaceAll(',','-');
                notification({title : pathName, message : info.data.operateResults}, 'info');
                return;
            }
            var msg = info.data.operateType ==1?'开闸失败':'关闸失败';
            notification({title : msg, message : info.data.operateResults}, 'info');
        }
    },
    openSuccess : function() {
        //$.growlUI('通信开启', 'Have a nice day!');
        tips = true;
        layer.open({
            type: 1,
            //time:1500,
            title: false,
            shade: 0,
            offset: 'rb',
            //closeBtn: 0,
            shadeClose: false,
            area: ['300px', '200px'],
            skin: 'layui-layer-rim', //加上边框
            content: '<div class="layuiCon">通道连接成功,<br>开始接收通道收发数据...</div>'
        });
    },
    onClose:function () {
        tips = false;
        notification({title : "通道数据接收失败", message : "连接断开，请检查设备、网络是否正常,关闭页面再试"}, 'info');
    },
    openRealVideo:function(ax,jsonData){
        if(isEmpty(jsonData.ipAddress) || isEmpty(jsonData.port)){
            return 0;
        }
        var handle = null;
        try{
            this.showVideo(ax,jsonData);
            var video = ax.find("object")[0];
            if(jsonData["deviceType"] == 1){
                handle = video.VzLPRClientOpen(jsonData.ipAddress, jsonData.port, jsonData.userName, jsonData.pwd);
                video.VzLPRClientStartPlay(handle, 0);
            }else{
                video.ipstr = jsonData.ipAddress;
            }
        }catch (e) {
            console.log("error: "+e.name);
            console.log("error: "+e.message);
        }
        videoMap.put(jsonData.code,handle);
        return handle;
    },
    closeRealVideo:function(ax,handle){
        try{
            var video = ax.find("object")[0];
            video.ipstr = "";
            video.VzLPRClientClose(handle);
            video.VzLPRClientStopPlay(0);
        }catch (e) {
            console.log("error: "+e.name);
            console.log("error: "+e.message);

        }
    },
    /**
     * 显示打开视频
     */
    showVideo:function(ax,jsonData){
        var newAx = null;
        if(jsonData["deviceType"] == 1){
            newAx = $('<object classid="clsid:CD72B5E0-33C4-425D-A950-26E76E03C67B" codebase="plugIn/VZLPRClientCtrl.cab#version=1,0,0,54" width="100%" height="100%"></object>');
        }else{
            newAx = $('<object classid="clsid:5D0BE7DE-4BC2-4F92-A3BA-F977F62BB15C" codebase="plugIn/axclient.cab" width="100%" height="100%"></object>');
        }
        //初始化单个摄像头框只有一个格子
        ax.empty().append(newAx);
        var that=this;
        setTimeout(function(){
            try {
                if(jsonData["deviceType"] == 1){
                    newAx[0].SetWindowStyle(1);
                }
            } catch (e) {
                ax.empty().append($("<img src='SMCP/monitor/videoMonitor/img/noSignal.png'  style='width:100%;height: 100%;'>"));
                if(!!window.ActiveXObject || "ActiveXObject" in window){
                    notification({title : "查看失败", message : "查看视频请先安装视频插件"}, 'info');
                }else{
                    notification({title : "查看失败", message : "查看视频请使用IE浏览器"}, 'info');
                }
            }
        },100);
    },
}